<template>
  <div id="mynetwork" style="height:600px"></div>
</template>
<script>
  import { Network, vis, DataSet } from 'vis';
  export default {
    name: 'flow',
    computed: {
      container() {
        return document.getElementById('mynetwork');
      },
      network() {
        var options = {
          layout: {
            hierarchical: {
              sortMethod: 'directed',
              direction: 'LR',
              enabled: true
            }
          },
          nodes: {
            shape: 'box',
            font: {
              bold: {
                color: '#0077aa'
              }
            }
          },
          edges: {
            smooth: true,
            arrows: { to: true }
          }
        };

        /**
         layout: {
            hierarchical: {
              sortMethod: 'directed',
              direction: 'LR',
              enabled: true
            }
          },
          edges: {
            smooth: true,
            arrows: { to: true }
          }
        **/

        return new Network(this.container, {}, options);
      }
    },
    props: {
      id: String
    },
    data() {
      return {
        dataList: []
      };
    },
    watch: {
      dataList() {
        // 当数据变动时，重新绘制
        this.draw();
      }
    },
    mounted() {
      this.getList(this.id);
    },
    methods: {
      // 绘制图
      draw() {
        let nodeList = [];
        let edgeList = [];

        for (let i = 0; i < this.dataList.length; i++) {
          let d = this.dataList[i];

          // 如果是调用
          if (d.type == 1) {
            edgeList[edgeList.length] = {
              from: d.className + '.' + d.methodName,
              to: d.invokeClass + '.' + d.invokeMethodName
            };
          } else {
            nodeList[nodeList.length] = {
              id: d.className + '.' + d.methodName,
              label: d.line + '_' + (d.name ? d.name : d.methodName),
              color: mColor(d)
            };
          }
        }

        // 转换m节点颜色
        function mColor(m) {
          if (m.layerWeight == 0) {
            return 'red';
          } else if (m.layer == 'service') {
            return 'yellow';
          } else if (m.layer == 'DBTable') {
            return 'green';
          } else {
            return '#D2E5FF';
          }
        }

        console.log(nodeList);
        console.log(edgeList);

        var nodes = new DataSet(nodeList);

        // create an array with edges
        var edges = new DataSet(edgeList);

        // provide the data in the vis format
        let data = {
          nodes: nodes,
          edges: edges
        };

        console.log(data);

        // 设置数据
        this.network.setData(data);
      },
      getList(id) {
        this.$http({
          url: '/grap/queryFriendDrawById/' + id,
          method: 'get'
        }).then(({ data }) => {
          this.dataList = data;
        });
      }
    }
  };
</script>
